package com.whl.sm.common.util;


import com.whl.sm.common.util.imgCompressUtil.ImgCompressUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;


public final class UploadUtils {

    private static final Logger log = LoggerFactory.getLogger(UploadUtils.class);

    private static final int BUFFER_SIZE = 1024 * 1024;

    public static void copy(MultipartFile src, File dst) {
        try {
            InputStream in = null;
            OutputStream out = null;

            try {
                in = new BufferedInputStream(src.getInputStream(),(int) src.getSize());
                out = new BufferedOutputStream(new FileOutputStream(dst),(int) src.getSize());
                byte[] buffer = new byte[(int) src.getSize()];
                while (in.read(buffer) > 0) {
                    out.write(buffer);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String saveFile(MultipartFile filename, String path, String name, HttpServletRequest request) throws Exception {
        File filePage = new File(pathDir(request, path), name);
        UploadUtils.copy(filename, filePage);
        return path + "/" + name;
    }


    /**
     * 不压缩
     *
     * @param filename  Spring mvc 的文件名
     * @param path      路径
     * @param imagename 新生成的图片名字
     * @param ext       图片类型
     * @param request
     * @throws Exception
     */
    public static void saveImageFile(MultipartFile filename, String path, String imagename, String ext, HttpServletRequest request) throws Exception {

        String pathdir = path;
        File filepage = new File(pathDir(request, pathdir), imagename);
        UploadUtils.copy(filename, filepage);
    }


    /**
     * 压缩成等比
     *
     * @param filename  Spring mvc 的文件名
     * @param path      路径
     * @param imagename 新生成的图片名字
     * @param ext       图片类型
     * @param request
     */
    public static void saveImageFile(MultipartFile filename, String path, String imagename, String ext, int size, HttpServletRequest request) throws Exception {

        String pathdir = path;
        Image srcFile = ImageIO.read(filename.getInputStream());
        File filepage = new File(pathDir(request, pathdir), imagename);
        String pathdirWidth = pathdir + "/" + size;

        UploadUtils.copy(filename, filepage);

        if (srcFile.getWidth(null) >= size || srcFile.getHeight(null) >= size) {
            saveTypeImage(filepage, pathdirWidth, imagename, size, ext, request, true);
        } else {
            File file = new File(pathDir(request, pathdirWidth), imagename);
            UploadUtils.copy(filename, file);
        }
    }


    private static String pathDir(HttpServletRequest request, String pathdir) {
        File saveDir = new File(pathdir);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }
        return pathdir;
    }


    /**
     * 上传附件到指定目录，支持上传多附件
     * path 自定义，灵活配置上传文件目录
     * rootFilePath 上传文件的基础路径， 完整上传路径为 rootFilePath + path
     *
     * */
    public static java.util.List<Map<String, Object>> saveFile(HttpServletRequest request, String path, String rootFilePath) {
        java.util.List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = null;
        try {
            MultipartHttpServletRequest multipartRequest = null;
            if(request instanceof MultipartHttpServletRequest){
                multipartRequest = (MultipartHttpServletRequest) request;
            }

            Set<MultipartFile> fileset = new LinkedHashSet<>();
            if(multipartRequest != null){
                for (Iterator it = multipartRequest.getFileNames(); it.hasNext(); ) {
                    String key = (String) it.next();
                    java.util.List<MultipartFile> fileList = multipartRequest.getMultiFileMap().get(key);
                    if(fileList != null && fileList.size() > 0){
                        for (MultipartFile file : fileList){
                            if(file != null && file.getOriginalFilename().length() > 0){
                                fileset.add(file);
                            }
                        }
                    }
                }
            }

            if (fileset.size() > 0) {
                for (MultipartFile myFile : fileset) {
                    if (!myFile.isEmpty()) {
                        String fileName = myFile.getOriginalFilename();
                        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                        String name = UUID.randomUUID() + "." + ext;
                        UploadUtils.saveFile(myFile, rootFilePath + path, name, multipartRequest);
                        map = new HashMap<>();
                        map.put("originalName", fileName);
                        map.put("fileName", name);
                        map.put("filePath", path + "/" +  name);
                        map.put("fileSize", myFile.getSize());
                        map.put("mimeType", myFile.getContentType());
                        list.add(map);
                    }
                }
            }
        } catch (Exception ex) {
            log.error("异常：  {}", ex);
        }
        return list;
    }





    /**
     * 上传附件到指定目录，支持上传多附件
     * path 自定义，灵活配置上传文件目录
     * rootFilePath 上传文件的基础路径， 完整上传路径为 rootFilePath + path
     * fileName 前端传过来的附件名称
     * */
    public static java.util.List<Map<String, Object>> saveFile(HttpServletRequest request, String path, String rootFilePath, String fileName) {
        java.util.List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = null;
        try {
            MultipartHttpServletRequest multipartRequest = null;
            if(request instanceof MultipartHttpServletRequest){
                multipartRequest = (MultipartHttpServletRequest) request;
            }

            Set<MultipartFile> fileset = new LinkedHashSet<>();
            if(multipartRequest != null){
                List<MultipartFile> fileList = multipartRequest.getMultiFileMap().get(fileName);
                if(fileList != null && fileList.size() > 0){
                    for (MultipartFile file : fileList){
                        if(file != null && file.getOriginalFilename().length() > 0){
                            fileset.add(file);
                        }
                    }
                }
            }

            if (fileset.size() > 0) {
                for (MultipartFile myFile : fileset) {
                    if (!myFile.isEmpty()) {
                        String originalFilename = myFile.getOriginalFilename();
                        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                        String name = UUID.randomUUID() + "." + ext;
                        UploadUtils.saveFile(myFile, rootFilePath + path, name, multipartRequest);
                        map = new HashMap<>();
                        map.put("originalName", originalFilename);
                        map.put("fileName", name);
                        map.put("fileSize", myFile.getSize());
                        map.put("filePath", path + "/" +  name);
                        map.put("mimeType", myFile.getContentType());
                        list.add(map);
                    }
                }
            }
        } catch (Exception ex) {
            log.error("异常：  {}", ex);
        }
        return list;
    }


    private static void saveTypeImage(File filepage, String pathdir_resize, String imagename, int width, String ext, HttpServletRequest request, Boolean flag) {

        // String realpathdir_resize="D:/server/nginx/webapps"+pathdir_resize;

       /* String realpathdir_resize = request.getSession().getServletContext()
                .getRealPath(pathdir_resize);*/
        File savedir_resize = new File(pathdir_resize);
        if (!savedir_resize.exists()) {
            savedir_resize.mkdirs();
        }

        //ImageSizer.resize(filepage, new File(savedir_resize, imagename), width, ext, flag);
        try{
            Image srcFile = ImageIO.read(filepage);
            int widthOld = srcFile.getWidth(null);
            int heightOld = srcFile.getHeight(null);
            Double height = heightOld*((double) width/widthOld);
            ImgCompressUtil.zoom(filepage.getPath(),pathdir_resize+File.separator+imagename,width,height.intValue());
        }catch (Exception e){
            log.error("压缩图片出错,{}",e);
        }
    }
}
